package com.emovimento.synchronize;

import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;

import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;

public abstract class DirectoryWatcher implements Watcher {
  private static Logger LOGGER = Logger.getLogger("Synchronization");

  private final WatchService watcher;
  private final BidiMap<WatchKey, Path> watchKeys = new DualHashBidiMap<>();
  protected AtomicBoolean goOnWatching = new AtomicBoolean(true);

  /**
   * Constructs a RecursiveDirectoryWatcher for the given directories. Watches the given directories and its sub-directories for change
   * events until the directory is deleted itself. Automatically registers sub-directories when they are created. Write subclasses if you
   * want to be notified on specific events.
   * 
   * @param directory the Path to watch
   * @throws IOException
   */
  public DirectoryWatcher(Path... directories) throws IOException {
    watcher = FileSystems.getDefault().newWatchService();

    for (Path directory : directories) {
      LOGGER.info("Scanning " + directory + " ...");
      registerAll(directory);
      LOGGER.info("Scanning finished.");
    }
  }

  /**
   * Registers the given directory, and all its sub-directories, to be notified on changes.
   */
  private void registerAll(final Path start) throws IOException {
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        register(dir);
        return FileVisitResult.CONTINUE;
      }
    });
  }

  protected void register(final Path path) throws IOException {
    watchKeys.put(path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY), path);
  }

  protected boolean unregister(final Path path) {
    WatchKey key = watchKeys.getKey(path);
    if (key == null) return false;
    key.cancel();
    watchKeys.remove(key);
    return true;
  }

  @Override
  public void watchInBackgroundThread() {
    Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          watch();
        } catch (NoSuchFileException e) {
          LOGGER.info("Stop watching no longer existing " + e.getFile());
          stopWatching();
        } catch (AccessDeniedException e) {
          LOGGER.info("Stop watching inaccessable " + e.getFile());
          stopWatching();
        } catch (Exception e) {
          LOGGER.severe("Exception occurred while watching directory " + e);
        }
      }
    });
    thread.setPriority(Thread.MIN_PRIORITY);
    thread.setDaemon(true);
    thread.start();
  }

  @Override
  public void stopWatching() {
    goOnWatching.lazySet(false);
  }

  protected void watch() throws IOException {
    while (goOnWatching.get() && !watchKeys.isEmpty()) {
      WatchKey watchKey = waitForSignal();
      if (watchKey == null) continue;
      Path signalledDirectory = watchKeys.get(watchKey);
      if (signalledDirectory == null) {
        LOGGER.warning("Synchronized directory was changed while copyig to it --> NEVER change one directory on both sides simultanuously");
        continue; // can happen when we change a directory while we copy to it --> just ignore such changes
      }
      // for now...
      processEvents(watchKey, signalledDirectory);

      if ( !watchKey.reset()) { // reset key and remove from set if directory no longer accessible
        watchKeys.remove(watchKey);
      }
    }
    watchKeys.clear();
  }

  /**
   * Process all events for watchKeys queued to the watcher
   * 
   * @throws IOException
   */
  void processEvents(final WatchKey watchKey, final Path directory) throws IOException {
    assert watchKey != null : "Can't process events for null watch key";
    assert directory != null : "Can't process events for null directory";

    for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
      Kind<?> kind = watchEvent.kind();

      // TBD - provide example of how OVERFLOW event is handled
      if (kind == OVERFLOW) {
        continue;
      }

      Path child = directory.resolve((Path) watchEvent.context());

      // print out event
      LOGGER.finest("" + kind.name() + ": " + child);

      // if directory is created, then
      // register it and its sub-directories
      if (kind == ENTRY_CREATE && Files.isDirectory(child, NOFOLLOW_LINKS)) {
        registerAll(child);
      }

      processEvent(kind, watchEvent, directory, child);
    }
  }

  /**
   * @param kind
   * @param watchEvent
   * @param child
   * @throws IOException
   */
  private void processEvent(final Kind<?> kind, final WatchEvent<?> watchEvent, final Path directory, final Path child) throws IOException {
    if (kind == ENTRY_CREATE) {
      entryCreated(watchEvent, directory, child);
      return;
    }
    if (kind == ENTRY_DELETE) {
      entryDeleted(watchEvent, directory, child);
      return;
    }
    if (kind == ENTRY_MODIFY) {
      entryModified(watchEvent, directory, child);
      return;
    }
    assert false : "No other types of kinds expected";
  }

  /**
   * Called whenever a new entry was created in the given directory. Does nothing per default. Implement specific behavior in subclasses
   * when needed.
   * 
   * @param watchEvent the WatchEvent which signaled the new entry creation.
   * @param directory the directory in which the new entry was created
   * @param createdPath the newly created entry
   * @throws IOException
   */
  protected void entryCreated(WatchEvent<?> watchEvent, final Path directory, final Path createdPath) throws IOException {
    // do nothing per default
  }

  /**
   * Called whenever an existing entry was deleted in the given directory. Does nothing per default. Implement specific behavior in
   * subclasses when needed.
   * 
   * @param watchEvent the WatchEvent which signaled the entry deletion.
   * @param directory the directory in which the entry was deleted
   * @param deletedPath the deleted entry
   * @throws IOException
   */
  protected void entryDeleted(WatchEvent<?> watchEvent, final Path directory, final Path deletedPath) throws IOException {
    // do nothing per default
  }

  /**
   * Called whenever an existing entry was modified in the given directory. Does nothing per default. Implement specific behavior in
   * subclasses when needed.
   * 
   * @param watchEvent the WatchEvent which signaled the entry modification.
   * @param directory the directory in which the entry was modified
   * @param modifiedPath the modified entry
   * @throws IOException
   */
  protected void entryModified(WatchEvent<?> watchEvent, final Path directory, final Path modifiedPath) throws IOException {
    // do nothing per default
  }

  /**
   * Waits for a signal from any of the watched directories.
   * 
   * @return a watch-key representing the signal or null if waiting failed (e.g. when closing down)
   */
  private WatchKey waitForSignal() {
    WatchKey key;
    try {
      key = watcher.take();
    } catch (InterruptedException | ClosedWatchServiceException e) {
      return null;
    }
    return key;
  }

}
